﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tomahawk.Runtime.Serialization;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Tomahawk.Runtime.Rendering.Materials
{
    public class SASMaterialCollection
    {
        [XmlAttribute("Name")]
        public string name = "Undefined";

        public SerializableDictionary<string, SASMaterialTemplate> materialTemplates = new SerializableDictionary<string,SASMaterialTemplate>();

        public T Build<T>(string templateName, string rootPath, ContentManager contentManager) where T : SASMaterial, new()
        {
            T sasEffect = null;
            SASMaterialTemplate template = null;
            if (materialTemplates.TryGetValue(templateName.ToUpper(), out template))
            {
                sasEffect = template.Build<T>(rootPath, contentManager);
            }

            return sasEffect;
        }

        #region Loading
        public static T Load<T>(string name, ContentManager contentManager) where T : SASMaterial, new()
        {
            T material = null;
            string[] tokens = name.Split(new char[] { '@' });
            if (tokens.Count() == 2)
            {
                SASMaterialCollection collection = contentManager.Load<SASMaterialCollection>(tokens[0]);
                if (collection != null)
                {
                    string rootPath = Path.GetDirectoryName(tokens[0]);
                    material = collection.Build<T>(tokens[1], rootPath, contentManager);
                }
            }
            return material;
        }
        #endregion

        #region Serialization
        public void Serialize(string file)
        {
            FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
            XmlSerializer x = new XmlSerializer(typeof(SASMaterialCollection));
            x.Serialize(fs, this);
        }

        public static SASMaterialCollection Deserialize(string file)
        {
            FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
            XmlSerializer x = new XmlSerializer(typeof(SASMaterialCollection));
            return (SASMaterialCollection)x.Deserialize(fs);
        }
        #endregion
    }
}
